package com.iapplize.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;

import com.iapplize.gcm.test.AllUsersActivity;
import com.iapplize.gcm.test.EnteringActivety;
import com.iapplize.gcm.test.R;
import com.iapplize.http.Parsing.xmlParser;
import com.iapplize.objects.GlobalVariables;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

public class HttpConnect extends AsyncTask<String, String, String> {

	int timeoutConnection = 15000;
	int timeoutSocket = 15000;

	String result = "";

	private Context context;

	public final static int GCM_SEND_MESSAGE = 0;
	public final static int GCM_SAVE_CLIENT = 1;
	public final static int GCM_GET_USER_LIST = 2;
	

	private final String STRING_GCM_SEND_MESSAGE = "gcm_send_message";
	private final String STRING_GCM_SAVE_CLIENT = "gcm_save_client";
	private final String STRING_GCM_GET_USER_LIST = "gcm_get_user_list";

	public final static int ERROR_ALL_OK = 0;
	public final static int ERROR_LOCATION_NOT_FOUND = 1;
	public final static int ERROR_RESPONSE_STATUS_CODE = 2;
	public final static int ERROR_UnsupportedEncodingException = 3;
	public final static int ERROR_ClientProtocolException = 4;
	public final static int ERROR_Exception = 5;

	private int selectedMethod;
	private int error = ERROR_ALL_OK;

	public HttpConnect(Context context, int Method) {

		this.setContext(context);
		this.selectedMethod = Method;

	}

	@Override
	protected String doInBackground(String... requestStrings) {

		HttpParams httpParameters = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParameters,
				timeoutConnection);
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

		HttpClient httpclient = new DefaultHttpClient(httpParameters);

		List<NameValuePair> nvps = new ArrayList<NameValuePair>();

		try {

			HttpPost httpost;
			HttpResponse response;

			switch (this.selectedMethod) {
			case GCM_SEND_MESSAGE:

				httpost = new HttpPost(GlobalVariables.getmainUrl() + STRING_GCM_SEND_MESSAGE);

				nvps.add(new BasicNameValuePair("regId", requestStrings[0]));
				nvps.add(new BasicNameValuePair("message", requestStrings[1]));

				httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

				response = httpclient.execute(httpost);

				if (response.getStatusLine().getStatusCode() == 200) {

					HttpEntity entity = response.getEntity();
					result = convertStreamToString(entity.getContent());

				} else {
					error = ERROR_RESPONSE_STATUS_CODE;
				}
				break;

			case GCM_SAVE_CLIENT:

				httpost = new HttpPost(GlobalVariables.getmainUrl() + STRING_GCM_SAVE_CLIENT);

				nvps.add(new BasicNameValuePair("regId", requestStrings[0]));
				nvps.add(new BasicNameValuePair("installationID",
						requestStrings[1]));
				nvps.add(new BasicNameValuePair("user_email", requestStrings[2]));

				httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

				response = httpclient.execute(httpost);

				if (response.getStatusLine().getStatusCode() == 200) {

					HttpEntity entity = response.getEntity();
					result = convertStreamToString(entity.getContent());

				} else {
					error = ERROR_RESPONSE_STATUS_CODE;
				}

				break;
				
			case GCM_GET_USER_LIST:

				httpost = new HttpPost(GlobalVariables.getmainUrl() + STRING_GCM_GET_USER_LIST);

				httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

				response = httpclient.execute(httpost);

				if (response.getStatusLine().getStatusCode() == 200) {

					HttpEntity entity = response.getEntity();
					result = convertStreamToString(entity.getContent());

				} else {
					error = ERROR_RESPONSE_STATUS_CODE;
				}

				break;
			}

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			error = ERROR_UnsupportedEncodingException;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			error = ERROR_ClientProtocolException;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			error = ERROR_Exception;
		} finally {
			httpclient.getConnectionManager().shutdown();
		}

		return result;

	}

	@Override
	protected void onPostExecute(String result) {

		Log.v("Server result", result);

		if (error == ERROR_ALL_OK) {

			switch (this.selectedMethod) {
			case GCM_SEND_MESSAGE:

				if (context instanceof EnteringActivety) {
					if (((EnteringActivety) context).spinnerDialog != null) {
						((EnteringActivety) context).spinnerDialog.cancel();
					}
				}else if (context instanceof AllUsersActivity) {
					if (((AllUsersActivity) context).spinnerDialog != null) {
						((AllUsersActivity) context).spinnerDialog.cancel();
					}
					
				}
				break;
			case GCM_SAVE_CLIENT:

				if (context instanceof EnteringActivety) {
					if (((EnteringActivety) context).spinnerDialog != null) {
						((EnteringActivety) context).spinnerDialog.cancel();

						if (result.trim().equalsIgnoreCase("ok")) {
							Intent intent = new Intent(
									((EnteringActivety) context),
									AllUsersActivity.class);
							context.startActivity(intent);
						}else{
							Toast.makeText(context, R.string.Server_error,
									Toast.LENGTH_SHORT).show();
						}

					}
				}
				break;
			case GCM_GET_USER_LIST:

				if (context instanceof AllUsersActivity) {
					if (((AllUsersActivity) context).spinnerDialog != null) {
						((AllUsersActivity) context).spinnerDialog.cancel();
					}
					
					xmlParser xp = new xmlParser();
					
					((AllUsersActivity) context).updateList(xp.parseUserData(result));
				}
				break;
				
			}
		}

	}

	private static String convertStreamToString(InputStream is) {

		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append((line + "\n"));
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	public String getSTRING_GCM_SEND_MESSAGE() {
		return STRING_GCM_SEND_MESSAGE;
	}

	public Context getContext() {
		return context;
	}

	public void setContext(Context context) {
		this.context = context;
	}

}
